package com.liuxing.calculation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import java.util.Map;

import static com.liuxing.calculation.Constant.JAVASCRIPT;

/**
 * desc: javascript动态脚本计算实现
 *
 * @author 刘磊
 * @since 2020/3/16
 */
@Slf4j
@Component("javascriptCalculationEngine")
public class JavascriptICalculationEngine extends ICalculationEngine {

    private ScriptEngine scriptEngine = null;

    @Override
    public Object calculate(String content, Map<String, Object> param) {
        try {
            return getEngine().eval(content, new SimpleBindings(param));
        } catch (ScriptException e) {
            log.error("执行脚本时出现异常：", e);
            return null;
        }
    }

    /**
     * 创建脚本引擎实例
     */
    private ScriptEngine getEngine() {
        if (scriptEngine == null) {
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            return scriptEngineManager.getEngineByName(JAVASCRIPT);
        } else {
            return scriptEngine;
        }
    }
}
